﻿"""
设置ini文件
"""
import configparser
import pandas as pd

# 创建实例对象
ini_file = configparser.ConfigParser()
position_file = configparser.ConfigParser()


def del_null(x):
    if x and not pd.isna(x):
        return x
    else:
        return ''


# 读取初始化ini文件
def ini_file_read(path):
    ini_file.read(path, encoding='gbk')


# 读取ini文件，交换信息
def position_file_read(path):
    position_file.read(path, encoding='gbk')


# 保存ini文件
def ini_file_save(path):
    with open(path, 'w') as configfile:
        ini_file.write(configfile)


# 设置运动位置
def set_position():
    # 读取初始化配置文件，移除position和clamp章节
    ini_file.remove_section('Position')
    ini_file.remove_section('Clamp')

    # 读取上传配置文件的position和clamp章节并赋值给初始化配置文件
    ini_file.read_dict({'Position': dict(position_file.items('Position'))})
    ini_file.read_dict({'Clamp': dict(position_file.items('Clamp'))})


# 补粉,连片设置电流电压
def set_voltage_current(voltage, current):
    # 修改配置文件的电流电压
    ini_file.set('Condtion', 'Voltage', f"{float(voltage):.2f}")
    ini_file.set('Condtion', 'Current', f"{float(current):.2f}")


# 补粉机设置校准系数
def set_cal_factor(coef_data):
    # 修改xy坐标
    ini_file.set('Factor', '6', "1,0.0000/0.0000,0.0000/0.0000,1.0000/1.0000,"
                                f"{coef_data['dx']:.4f}/{coef_data['dy']:.4f},"
                                '1.0000/1.0000,0.0000/0.0000,1.0000/1.0000,0.0000/0.0000')
    # 修改光通量
    ini_file.set('Factor', '9', f"1,0.0000,0.0000,{coef_data['dlm']:.4f},0.0000,1.0000,0.0000,1.00000,0.0000")
    # 修改电压,Ra，R9
    factor_index = {'dU': 1, 'dRa': 10, 'dR9': 31}
    for i in factor_index.items():
        ini_file.set('Factor', f'{i[1]}', f'1,0.0000,0.0000,1.00000,{coef_data[i[0]]:.4f},1.0000,0.0000,1.00000,0.0000')


# 补粉设置成品参数范围
def set_range(bin_range, range_data, flag):
    max = 0
    for i in range_data.itertuples():
        if getattr(i, 'Parameter') == 'SDCM':
            max = getattr(i, 'USL')
    range_index = {'LuminousFlux_lm': 9, 'ForwardVoltage_V': 1, 'SDCM': 19, 'Ra': 10, 'R9': 31}
    for i in range_index.items():
        if i[0] in list(range_data['Parameter']):
            # 以SDCM分级的范围 固定为0~2
            if i[0] == 'SDCM':
                if flag:
                    ini_file.set('Range', f'{i[1]}', '0,1,10')
                else:
                    if max == 1:
                        ini_file.set('Range', f'{i[1]}', '1,0,1,10')
                    elif max == 1.5 or max == 2:
                        ini_file.set('Range', f'{i[1]}', '1,0,1.5,10')
                    elif max == 3:
                        ini_file.set('Range', f'{i[1]}', '1,0,2,10')
            else:
                # 判断有范围值再设置
                if range_data[range_data['Parameter'] == i[0]]['USL'].to_list()[0]:
                    ini_file.set('Range', f'{i[1]}',
                                 f"1,{range_data[range_data['Parameter'] == i[0]]['LSL'].to_list()[0]},"
                                 f"{range_data[range_data['Parameter'] == i[0]]['USL'].to_list()[0]},10")


# 补粉设置色容差bin
def set_mac_bin(bin_range, range_data, flag):
    """

    :param bin_range:
    :param range_data:
    :param flag: 从2828基板的标志，改为判断选项
    :return:
    """
    id_list=[]
    name_list=[]
    xy_dict={}
    lm_dict={}
    sdcm_dict={}
    final_dict = {}
    for i in bin_range.itertuples():
        if getattr(i, 'BinID') not in id_list:
            id_list.append(getattr(i, 'BinID'))
        if getattr(i, 'BinName') not in name_list:
            name_list.append(getattr(i, 'BinName'))
        if getattr(i, 'Parameter') == 'CIExy':
            xy_dict[getattr(i, 'BinID')] = f"{getattr(i, 'LSL')},{getattr(i, 'USL')},{getattr(i, 'CIEx2')}," \
                                           f"{getattr(i, 'CIEy2')},{getattr(i, 'CIEx3')},{getattr(i, 'CIEy3')}," \
                                           f"{getattr(i, 'CIEx4')},{getattr(i, 'CIEy4')}"
        elif getattr(i, 'Parameter') == 'LuminousFlux_lm':
            lm_dict[getattr(i, 'BinID')] = f"{getattr(i, 'LSL')},{getattr(i, 'USL')}"
    if 'SDCM' in list(range_data['Parameter']):
        if range_data[range_data['Parameter'] == 'SDCM']['USL'].tolist()[0] == '1' and flag == '3':
            sdcm_dict[1]="0,0.5"
            sdcm_dict[2]="0.5,0.8"
            sdcm_dict[3]="0.8,1"
        else:
            sdcm_dict[1] = "0,0.5"
            sdcm_dict[2] = "0.5,1"
            sdcm_dict[3] = "1,1.5"
    if xy_dict:
        ini_file.set('BinSel', '6', '1')
        for i in xy_dict.keys():
            final_dict[i] = xy_dict.get(i)
    if lm_dict:
        ini_file.set('BinSel', '17', '1')
        if xy_dict:
            for i in lm_dict.keys():
                final_dict[i] += ','+str(lm_dict.get(i))
        else:
            for i in lm_dict.keys():
                final_dict[i] = lm_dict.get(i)
    if sdcm_dict:
        ini_file.set('BinSel', '19', '1')
        if xy_dict or lm_dict:
            for i in sdcm_dict.keys():
                final_dict[i] += ','+str(sdcm_dict.get(i))
        else:
            for i in sdcm_dict.keys():
                final_dict[i] = sdcm_dict.get(i)
    for binid,name in zip(id_list,name_list):
        ini_file.set('BinData',f"{binid}",f"{binid},{name},-8323200,{final_dict[binid]}")
        
# 设置成品颜色标准
def set_color_stand(color_data, color_data2=pd.DataFrame()):
    if 'Data' not in ini_file.sections():
        ini_file.add_section('Data')
    ini_file.set('Data', '1',
                 f"{color_data.loc[0, 'CCT_code_alias']}({color_data.loc[0, 'CCT_STANDARD']}),1,"
                 f"{color_data.loc[0, 'a']},{color_data.loc[0, 'b']},{color_data.loc[0, 'θ']},"
                 f"{color_data.loc[0, 'CIEx']},{color_data.loc[0, 'CIEy']}")
    if not color_data2.empty:
        ini_file.set('SDCM', 'count', '2')
        ini_file.set('Data','2',
                     f"{color_data2.loc[0, 'CCT_CODE']},1,"
                     f"{color_data2.loc[0, 'a']},{color_data2.loc[0, 'b']},{color_data2.loc[0, 'θ']},"
                     f"{color_data2.loc[0, 'CIEx']},{color_data2.loc[0, 'CIEy']}")


# 设置湿胶参数范围
def set_wet_range(range_data):
    range_index = {'Wet_Glue_lm': 9, 'Wet_Glue_Ra': 10, 'Wet_Glue_R9': 31}
    for i in range_index.items():
        if range_data.loc[0, i[0]]:
            ini_file.set('Range', f'{i[1]}', f"1,{range_data.loc[0, i[0]]},{abs(range_data.loc[0, i[0]] * 10)},10")
        else:
            ini_file.set('Range', f'{i[1]}', f"0,,,10")


# 设置小批量与量产湿胶颜色标准
def set_wet_xy(color_data, wet_xy, pes):
    # 1为小批量
    if pes == '1':
        ini_file.set('Data', '1',
                     f"{color_data.loc[0, 'CCT_code_alias']}({color_data.loc[0, 'CCT_STANDARD']}小批量),1,"
                     f"{color_data.loc[0, 'a']},{color_data.loc[0, 'b']},{color_data.loc[0, 'θ']},"
                     f"{wet_xy.loc[0, 'initial_CIEx']},{wet_xy.loc[0, 'initial_CIEy']}")
    # 2位量产湿胶
    elif pes == '2':
        ini_file.set('Data', '1',
                     f"{color_data.loc[0, 'CCT_code_alias']}({color_data.loc[0, 'CCT_STANDARD']}湿胶),1,"
                     f"{color_data.loc[0, 'a']},{color_data.loc[0, 'b']},{color_data.loc[0, 'θ']},"
                     f"{wet_xy.loc[0, 'Adjust_CIEx']},{wet_xy.loc[0, 'Adjust_CIEy']}")

    else:
        pass

# if __name__ == '__main__':
# ini_file_bac_read(r'ini\init00.ini')
# ini_file_read(r'ini\init00.ini')
# set_voltage_current(111, 222)
# ini_file_save(r'ini\配置.ini')
# print(ini_file.items('Condtion'))
